﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace PluginIdea
{
    public class MeshLineDraw : MonoBehaviour
    {
        private Mesh mesh;

        static Material lineMaterial;
        static void CreateLineMaterial()
        {
            if (!lineMaterial)
            {
                // Unity has a built-in shader that is useful for drawing
                // simple colored things.
                Shader shader = Shader.Find("Hidden/Internal-Colored");
                lineMaterial = new Material(shader);
                lineMaterial.hideFlags = HideFlags.HideAndDontSave;
                // Turn on alpha blending
                lineMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
                lineMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                // Turn backface culling off
                lineMaterial.SetInt("_Cull", (int)UnityEngine.Rendering.CullMode.Off);
                // Turn off depth writes
                lineMaterial.SetInt("_ZWrite", 0);
            }
        }

        void Start()
        {
            CreateLineMaterial();
            mesh = GetComponentInChildren<MeshFilter>().mesh;
        }

        void OnRenderObject()
        {
            if (Camera.current.name == "ScreenUICamera") return;
            //SuperController.LogMessage(Camera.current.name);

            lineMaterial.SetPass(0);     //设置用来渲染的pass

            GL.wireframe = true;     //是否显示线框

            GL.Color(new Color(1, 0, 0, 0.8F));
            GL.PushMatrix();
            GL.Begin(GL.TRIANGLES);
            for (int i = 0; i < mesh.triangles.Length - 2; i += 3)     //注意：这里mesh.triangles包含的具体的内容
            {
                GL.Vertex(transform.TransformPoint(mesh.vertices[mesh.triangles[i]]));
                GL.Vertex(transform.TransformPoint(mesh.vertices[mesh.triangles[i + 1]]));
                GL.Vertex(transform.TransformPoint(mesh.vertices[mesh.triangles[i + 2]]));
            }
            GL.End();
            GL.PopMatrix();

            GL.wireframe = false;     //这里务必设置，否则Scene窗口会显示异常
        }
    }

}

